<template>
  <div class="common-View">
    <common-table
      :loading="loading"
      :table-data="tableData"
      :table-prop="tableProp"
      :export-excel-data="exportExcelData"
      :module-name="moduleName"
      @searchData="searchData($event)"
      @addData="addData"
      @deleteData="deleteData($event)"
      @editData="editData($event)"
    />
    <!-- 添加修改的弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="400px"
      :before-close="handleClose"
    >
      <el-form ref="form" :rules="formRules" :model="form" label-width="100px">
        <!-- 用户表单 -->
        <el-form-item v-if="moduleName ==='userList'" label="学号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入学号" style="width:200px" />
        </el-form-item>

        <el-form-item v-if="moduleName ==='userList'" label="姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入姓名" style="width:200px" />
        </el-form-item>

        <el-form-item v-if="moduleName ==='userList'" label="身份证" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证" style="width:200px" />
        </el-form-item>

        <el-form-item v-if="moduleName ==='userList'" label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option
              v-for="item in sexList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="moduleName ==='userList'" label="班级" prop="classRoomId">
          <el-select v-model="form.classRoomId" placeholder="请选择班级">
            <el-option
              v-for="item in options.classroomDetailList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="moduleName ==='userList'" label="学制" prop="academicYear">
          <el-input v-model.number="form.academicYear" placeholder="请输入学制" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName ==='userList'" label="入学时间" prop="admissionYear">
          <el-date-picker
            v-model="form.admissionYear"
            style="width:150px"
            type="year"
            placeholder="选择年"
            value-format="yyyy"
          />
        </el-form-item>
        <!-- 角色表单 -->
        <el-form-item v-if="moduleName ==='roleList'" label="角色名称" prop="roleName">
          <el-select v-model="form.roleName" filterable placeholder="请选择">
            <el-option
              v-for="item in options.codeList.roleNameList"
              :key="item.id"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="moduleName ==='roleList' && form.roleName==='其他'" label="其他角色名" prop="customRoleName">
          <el-input v-model="form.customRoleName" placeholder="请输入自定义角色名称" style="width:200px" />
        </el-form-item>

        <el-form-item v-if="moduleName ==='roleList' " label="角色标识" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入角色标识" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName ==='roleList'" label="权限组" prop="permissionGroupIdList">
          <el-select v-model="form.permissionGroupIdList" filterable multiple placeholder="请选择">
            <el-option
              v-for="item in options.permissionGroupList"
              :key="item.id"
              :label="item.permissionGroupName"
              :value="item.permissionGroupName"
            />
          </el-select>
        </el-form-item>

        <el-form-item v-if="moduleName ==='roleList' " label="角色描述" prop="roleDesc">
          <el-input v-model="form.roleDesc" :rows="2" type="textarea" placeholder="请输入角色描述" style="width:200px" />
        </el-form-item>
        <!-- 权限组表单 -->
        <el-form-item v-if="moduleName ==='permissionGroupList'" label="权限组名称" prop="permissionGroupName">
          <el-input v-model="form.permissionGroupName" placeholder="请输入权限组名称" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName==='permissionGroupList'" label="拥有权限" prop="permissionIdList">
          <el-select v-model="form.permissionIdList" filterable style="width:250px" multiple placeholder="请选择权限">
            <el-option
              v-for="item in options.permissionList"
              :key="item.id"
              :label="item.permissionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="moduleName ==='permissionGroupList' " label="权限组描述" prop="permissionGroupDesc">
          <el-input v-model="form.permissionGroupDesc" :rows="2" type="textarea" placeholder="请输入角色描述" style="width:200px" />
        </el-form-item>
        <!-- 学院配置表单 -->
        <el-form-item v-if="moduleName ==='academyConfig'" label="学院名称" prop="academyName">
          <el-input v-model="form.academyName" placeholder="请输入学院名称" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName ==='academyConfig'" label="辅导员" prop="counselorId">
          <el-select v-model="form.counselorId" filterable style="width:200px" placeholder="请选择辅导员">
            <el-option
              v-for="item in options.userList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="moduleName ==='academyConfig'" label="院长" prop="deanId">
          <el-select v-model="form.deanId" filterable style="width:200px" placeholder="请选择院长">
            <el-option
              v-for="item in options.userList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="moduleName ==='academyConfig'" label="副院长" prop="associateDeanId">
          <el-select v-model="form.associateDeanId" style="width:200px" placeholder="请选择副院长">
            <el-option
              v-for="item in options.userList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 专业配置表单 -->
        <el-form-item v-if="moduleName ==='professionConfig'" label="专业名称" prop="professionName">
          <el-input v-model="form.professionName" placeholder="请输入专业名称" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName ==='professionConfig'" label="设立年份" prop="professionBuildYear">
          <el-date-picker
            v-model="form.professionBuildYear"
            style="width:150px"
            type="year"
            placeholder="选择年"
            value-format="yyyy"
          />
        </el-form-item>
        <el-form-item v-if="moduleName ==='professionConfig'" label="学院" prop="academyId">
          <el-select v-model="form.academyId" filterable style="width:200px" placeholder="请选择学院">
            <el-option
              v-for="item in options.academyList"
              :key="item.id"
              :label="item.academyName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 宿舍配置 -->
        <el-form-item v-if="moduleName ==='dormitoryConfig'" label="楼幢" prop="building">
          <el-input v-model.number="form.building" placeholder="请输入楼幢" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName ==='dormitoryConfig'" label="楼长" prop="dormitoryManagerId">
          <el-select v-model="form.dormitoryManagerId" filterable style="width:200px" placeholder="请选择楼长">
            <el-option
              v-for="item in options.userList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 班级表单 -->
        <el-form-item v-if="moduleName==='classRoomList'" label="年级" prop="classYear">
          <el-date-picker
            v-model="form.classYear"
            style="width:150px"
            type="year"
            placeholder="选择年"
            value-format="yyyy"
          />
        </el-form-item>
        <el-form-item v-if="moduleName==='classRoomList'" label="专业" prop="professionId">
          <el-select v-model="form.professionId" filterable placeholder="请选择专业">
            <el-option
              v-for="item in options.professionList"
              :key="item.id"
              :label="item.professionName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="moduleName==='classRoomList'" label="班级编号" prop="classCode">
          <el-input v-model.number="form.classCode" placeholder="班级编号" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName==='classRoomList'" label="班主任" prop="classTeacherId">
          <el-select v-model="form.classTeacherId" filterable placeholder="请选择班主任">
            <el-option
              v-for="item in options.userList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- 住宿表单 -->
        <el-form-item v-if="moduleName ==='roomList'" label="楼幢" prop="dormitoryId">
          <el-select v-model="form.dormitoryId" filterable style="width:200px" placeholder="请选择楼幢">
            <el-option
              v-for="item in options.dormitoryList"
              :key="item.id"
              :label="item.building+'幢'"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="moduleName ==='roomList'" label="门牌号" prop="tablet">
          <el-input v-model.number="form.tablet" placeholder="请输入门牌号" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName ==='roomList'" label="床号" prop="bedNumber">
          <el-input v-model.number="form.bedNumber" placeholder="请输入床号" style="width:200px" />
        </el-form-item>
        <!-- 财务表单  -->
        <el-form-item v-if="moduleName ==='financeList'" label="用户" prop="userId">
          <el-select v-model="form.userId" filterable style="width:200px" placeholder="请选择用户">
            <el-option
              v-for="item in options.userList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="moduleName ==='financeList'" label="订单价格" prop="money">
          <el-input v-model.number="form.money" placeholder="请输入订单价格" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName ==='financeList'" label="订单名称" prop="orderName">
          <el-input v-model.number="form.orderName" placeholder="请输入订单名称" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName ==='financeList'" label="订单描述" prop="orderDesc">
          <el-input v-model.number="form.orderDesc" placeholder="请输入订单描述" style="width:200px" />
        </el-form-item>
        <!-- 场景表单  -->
        <el-form-item v-if="moduleName ==='sceneList'" label="名称" prop="sceneName">
          <el-input v-model.number="form.sceneName" placeholder="请输入名称" style="width:200px" />
        </el-form-item>
        <el-form-item v-if="moduleName ==='sceneList'" label="描述" prop="sceneDesc">
          <el-input v-model.number="form.sceneDesc" :rows="2" type="textarea" placeholder="请输入描述" style="width:200px" />
        </el-form-item>
        <el-form-item
          v-if="moduleName ==='sceneList'"
          label="图片"
          prop="sceneImage"
        >
          <el-upload
            ref="upload"
            action=""
            :limit="1"
            class="upload-demo"
            :on-change="handleChange"
            :on-exceed="onExceed"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')">确定</el-button>
          <el-button @click="dialogVisible=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-pagination
      style="float:right"
      :page-size="pageSize"
      layout="total, prev, pager, next, jumper"
      :total="total"
      :current-page="pageNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <choice-dormitory v-if="moduleName === 'roomList'" />
  </div>
</template>

<script>

import CommonTable from '../commonTable/index.vue'
import ChoiceDormitory from '../choiceDormitory/index.vue'
import { getAllProfession } from '@/api/profession'
import { getAllClassRoomDetail } from '@/api/classroom'
import { getAllPermission } from '@/api/permission'
import { getAllPermissionGroup } from '@/api/permission-group'
import { getAllUser } from '@/api/user'
import { getAllAcademy } from '@/api/academy'
import { getAllDormitory } from '@/api/dormitory'
import { getCodeList } from '@/api/code'

export default {
  name: 'CommonView',
  components: {
    'common-table': CommonTable,
    'choice-dormitory': ChoiceDormitory

  },
  props: {
    moduleName: {
      type: String, // classRoomList |
      default: ''
    },
    search: {
      type: Function,
      default: () => {}
    },
    add: {
      type: Function,
      default: () => {}
    },
    delete: {
      type: Function,
      default: () => {}
    },
    update: {
      type: Function,
      default: () => {}
    },
    tableProp: {
      type: Array,
      default: () => { return [] }
    },
    formRules: {
      type: Object,
      default: () => { return {} }
    },
    getFormData: {
      type: Function,
      default: () => {}
    },
    getSearchData: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      exportExcelData: [],
      fileList: [],
      sexList: [
        { value: '男', label: '男' },
        { value: '女', label: '女' }
      ],
      options: {
        userList: [],
        classroomDetailList: [],
        permissionList: [],
        permissionGroupList: [],
        academyList: [],
        professionList: [],
        dormitoryList: [],
        sceneList: [],
        // 代码表
        codeList: {}
      },
      loading: false,
      title: '',
      dialogVisible: false,
      tableData: [],
      pageSize: this.moduleName === 'roomList' ? 5 : 5,
      pageNum: 1,
      total: 0,
      form: {
        id: null,
        // 用户表单
        userName: '',
        nickName: '',
        idCard: '',
        sex: '',
        academicYear: null,
        admissionYear: null,
        classRoomId: null,
        // 角色表单参数
        roleName: '',
        customRoleName: '',
        roleCode: '',
        permissionGroupIdList: [],
        roleDesc: '',
        // 权限组表单参数
        permissionGroupName: '',
        permissionIdList: [],
        permissionGroupDesc: '',
        // 学院配置表单参数
        academyName: '',
        counselorId: null,
        deanId: null,
        associateDeanId: null,
        // 专业配置表单参数
        professionName: '',
        professionBuildYear: null,
        academyId: null,
        // 宿舍配置表单参数
        building: null,
        dormitoryManagerId: null,
        // 班级表单参数
        classYear: null,
        professionId: null,
        classCode: null,
        classTeacherId: null,
        // 住宿表单
        dormitoryId: null,
        tablet: null,
        bedNumber: null,
        // 财务表单
        userId: null,
        money: null,
        orderName: '',
        orderDesc: '',
        // 场景表单
        sceneName: '',
        sceneDesc: '',
        sceneImage: null
      }
    }
  },
  watch: {
  },
  mounted() {
    // 数据初始化一下
    this.getList()
    // 公共数据初始化，例如专业、班级等
    this.commonDataInit()
  },
  methods: {
    async getList(data) {
      this.loading = true
      var params = {}
      // 如果传数据，就是查询相应的参数
      if (data) {
        params = this.getSearchData(data)
      }
      params['pageSize'] = this.pageSize
      params['pageNum'] = this.pageNum
      const res = await this.search(params)
      const { list, total } = res
      const pageData = JSON.parse(JSON.stringify(list))
      this.exportExcelData = list
      // console.log(this.exportExcelData, 'excel')
      console.log(list, 'res')
      this.total = total
      this.tableData = pageData.splice(this.pageNum * 5 - 5, this.pageSize * this.pageNum)
      this.loading = false
    },
    addData() {
      this.title = '新增'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['form']?.resetFields()
      })
    },
    searchData(data) {
      this.getList(data)
    },
    editData(data) {
      this.title = '编辑'
      this.form = this.getFormData(data, 'edit', data.id)
      this.dialogVisible = true
    },
    deleteData(data) {
      // 传进来的data是数组，如data=[1,2,3]
      if (data.length < 1) {
        this.$message.error('请先选择需要删除的行')
      } else {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delete({ id: data.join(',') }).then(() => {
            this.$message.success('删除成功')
            setTimeout(() => {
              this.reload()
            }, 500)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    async commonDataInit() {
      try {
        // 这里是为了数据初始化，比如专业等，用于select组件
        // 但是需要优化，因为有些页面不需要请求,可以后端进行统一返回，后期再考虑

        // 这里有些需要传空的对象，因此，需要上述优化
        const [
          userList,
          professionList,
          permissionList,
          permissionGroupList,
          academyList,
          dormitoryList,
          classroomDetailList,
          codeList
        ] =
          await Promise.all([
            getAllUser(),
            getAllProfession(),
            getAllPermission(),
            getAllPermissionGroup(),
            getAllAcademy(),
            getAllDormitory(),
            getAllClassRoomDetail(),
            getCodeList()
          ])
        this.options.userList = userList
        this.options.professionList = professionList
        this.options.permissionList = permissionList
        this.options.permissionGroupList = permissionGroupList
        this.options.academyList = academyList
        this.options.dormitoryList = dormitoryList
        this.options.classroomDetailList = classroomDetailList
        // 下面是代码表，应该和上面一起的，后续修改
        this.options.codeList = codeList
      } catch (error) {
        console.log(error)
      }
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 这里需要判断是添加还是修改，添加走添加，修改走修改
          const formData = this.getFormData(this.form, 'add', null)
          console.log('转换后', formData)
          if (this.title === '新增') {
            this.add(formData).then(() => {
              this.dialogVisible = false
              this.$message.success('添加成功')
              setTimeout(() => {
                this.reload()
              }, 500)
            })
          } else if (this.title === '编辑') {
            this.update(this.form).then(() => {
              this.dialogVisible = false
              this.$message.success('修改成功')
              setTimeout(() => {
                this.reload()
              }, 500)
            })
          }
        } else {
          return false
        }
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getList()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.getList()
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    reload() {
      if (this.moduleName === 'sceneList') {
        this.$refs.upload.clearFiles()// 调用element官方的方法
      }
      this.getList()
    },
    handleChange(file, fileList) {
      const fileType = file.raw.type
      if (fileType !== 'image/jpeg' && fileType !== 'image/jpg') {
        this.$message.error('只能上传jpg/jpeg格式的图片')
        this.$refs.upload.clearFiles()// 调用element官方的方法
      } else {
        this.getBase64(file.raw).then(res => {
          this.form.sceneImage = res.replace('data:image/jpeg;base64,', '')
        })
      }
    },
    getBase64(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function() {
          imgResult = reader.result
        }
        reader.onerror = function(error) {
          reject(error)
        }
        reader.onloadend = function() {
          resolve(imgResult)
        }
      })
    },
    onExceed() {
      this.$message.error('只允许上传一张图片')
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
